package cn.scw.project.system.service.impl;

import cn.scw.common.constant.SysConsts;
import cn.scw.common.exception.CustomException;
import cn.scw.common.utils.SecurityUtils;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.bean.ToolUtils;
import cn.scw.common.utils.sql.JpaUtil;
import cn.scw.framework.aspectj.lang.annotation.DataScope;
import cn.scw.framework.web.domain.AjaxResult;
import cn.scw.project.facility.service.IFacPrintOrderService;
import cn.scw.project.system.domain.SysDealer;
import cn.scw.project.system.domain.SysUser;
import cn.scw.project.system.domain.netework.bean.SysDealerAddReq;
import cn.scw.project.system.domain.netework.bean.SysDealerListReq;
import cn.scw.project.system.domain.vo.SysDealerVo;
import cn.scw.project.system.mapper.SysDealerMapper;
import cn.scw.project.system.service.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 经销商Service业务层处理
 *
 * @author api
 * @date 2020-05-20
 */
@Service
public class SysDealerServiceImpl implements ISysDealerService {
    @Autowired
    private SysDealerMapper sysDealerMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IFacPrintOrderService iFacPrintOrderService;
    @Autowired
    private ISysUserBrokerageService iSysUserBrokerageService;
    @Autowired
    private ISysPostService iSysPostService;
    @Autowired
    private ISysDealerService iSysDealerService;

    /**
     * 查询经销商
     *
     * @param id 经销商ID
     * @return 经销商
     */
    @Override
    public SysDealer selectSysDealerById(Long id) {
        return sysDealerMapper.selectSysDealerById(id);
    }

    @Override
    public SysDealerVo selectSysDealerVoById(Long id) {
        return sysDealerMapper.selectSysDealerVoById(id);
    }

    @Override
    public SysDealer selectSysDealerByUserId(Long userId) {
        return sysDealerMapper.selectSysDealerByUserId(userId);
    }

    /**
     * 查询经销商列表
     *
     * @param req 经销商
     * @return 经销商
     */
    @Override
    public List<SysDealerVo> selectSysDealerList(SysDealerListReq req) {
        req.setName(JpaUtil.getNullOrLikeStr(req.getName()));
        req.setPhone(JpaUtil.getNullOrLikeStr(req.getPhone()));

        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(user != null) {
            System.out.println("selectSysDealerList user id=" + user.getUserId());
        }
        SysDealer dealer = iSysDealerService.selectSysDealerByUserId(user.getUserId());
        if (dealer != null)
        {
            System.out.println("selectSysDealerList dealer id=" + dealer.getId());
            req.setPuserId(dealer.getId());
        }else{
            System.out.println("selectSysDealerList dealer is not found");
        }

        return sysDealerMapper.selectSysDealerList(req);
    }

    /**
     * 新增经销商
     *
     * @param req 经销商
     * @return 结果
     */
    @Override
    public int insertSysDealer(SysDealerAddReq req) {
        SysUser user = sysUserService.selectUserById(req.getUserId());
        if (user == null)
            throw new CustomException("用户不存在");
        if (this.existsByUserId(req.getUserId()))
            throw new CustomException("此用户已是经销商");
        if (StringUtils.isBlank(req.getName()))
            throw new CustomException("请输入经销商姓名");
        if (StringUtils.isBlank(req.getPhone()))
            throw new CustomException("请输入经销商电话");
        if (StringUtils.isBlank(req.getAddress()))
            throw new CustomException("请输入经销商地址");
        if (req.getCommissionRate() == null || req.getCommissionRate() <= 0 || req.getCommissionRate() > 100)
            throw new CustomException("请设置正确的佣金比例");
        if (req.getJurisPrice() == null)
            throw new CustomException("请设置价格修改权限");
        if (req.getJurisAdvertising() == null)
            throw new CustomException("请设置广告修改权限");
        if (req.getJurisWithdraw() == null)
            throw new CustomException("请设置微信提现权限");
//        if (!sysDictDataService.existsDictLabel(DictTypeConsts.SYS_DEALER_LEVEL, req.getLevel()))
//            throw new CustomException("请选择正确的经销商级别");
        if (StringUtils.isBlank(req.getPositionProvince()))
            throw new CustomException("请选择代理位置和级别");
        if (StringUtils.isNotBlank(req.getPositionArea()))
            req.setLevel(SysConsts.DEALER_LEVEL_AREA);
        else if (StringUtils.isNotBlank(req.getPositionCity()))
            req.setLevel(SysConsts.DEALER_LEVEL_CITY);
        else
            req.setLevel(SysConsts.DEALER_LEVEL_PROVINCE);
        SysDealer sysDealer = new SysDealer();
        ToolUtils.copyPropertiesIgnoreNull(req, sysDealer);
        // 添加经销商后设置部门权限
        user.setPostIds(new Long[]{4L});
        user.setRoleIds(new Long[]{2L});
        sysUserService.updateUser(user);
        // 设置父级经销商
        SysUser curruser = SecurityUtils.getLoginUser().getUser();
        if(curruser != null) {
            System.out.println("insertSysDealer user id=" + curruser.getUserId());
        }

        SysDealer dealer = iSysDealerService.selectSysDealerByUserId(curruser.getUserId());
        if (dealer != null){
            System.out.println("insertSysDealer dealer id=" + dealer.getId());
            sysDealer.setPuserId(dealer.getId());
        }else{
            System.out.println("insertSysDealer dealer not found");
        }



        return sysDealerMapper.insertSysDealer(sysDealer);
    }

    private boolean existsByUserId(Long userId) {
        return this.sysDealerMapper.existsByUserId(userId);
    }

    /**
     * 修改经销商
     *
     * @param req 经销商
     * @return 结果
     */
    @Override
    public int updateSysDealer(SysDealerAddReq req) {
        SysDealer sysDealer = this.selectSysDealerById(req.getId());
        ToolUtils.copyPropertiesIgnoreNull(req, sysDealer);
        SysUser user = sysUserService.selectUserById(req.getUserId());
        if (user == null)
            throw new CustomException("用户不存在");
        if (req.getCommissionRate() == null || req.getCommissionRate() <= 0 || req.getCommissionRate() > 100)
            throw new CustomException("请设置正确的佣金比例");
//        if (!sysDictDataService.existsDictLabel(DictTypeConsts.SYS_DEALER_LEVEL, req.getLevel()))
//            throw new CustomException("请选择正确的经销商级别");
        if (StringUtils.isNotBlank(req.getPositionArea()))
            sysDealer.setLevel(SysConsts.DEALER_LEVEL_AREA);
        else if (StringUtils.isNotBlank(req.getPositionCity())) {
            sysDealer.setLevel(SysConsts.DEALER_LEVEL_CITY);
            sysDealer.setPositionArea(null);
        } else {
            sysDealer.setLevel(SysConsts.DEALER_LEVEL_PROVINCE);
            sysDealer.setPositionArea(null);
            sysDealer.setPositionCity(null);
        }
        return sysDealerMapper.updateSysDealer(sysDealer);
    }

    /**
     * 批量删除经销商
     *
     * @param ids 需要删除的经销商ID
     * @return 结果
     */
    @Override
    public int deleteSysDealerByIds(Long[] ids) {
        return sysDealerMapper.deleteSysDealerByIds(ids);
    }

    /**
     * 删除经销商信息
     *
     * @param id 经销商ID
     * @return 结果
     */
    @Override
    public int deleteSysDealerById(Long id) {
        return sysDealerMapper.deleteSysDealerById(id);
    }

    @Override
    public AjaxResult count() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDealer dealer = sysDealerMapper.selectSysDealerByUserId(user.getUserId());
        double allCount, dealerCount;
        if (dealer != null) {
            allCount = iFacPrintOrderService.countAllByDealer(dealer);
            dealerCount = iSysUserBrokerageService.countAllByDealer(user);
        } else {
            dealer = new SysDealer();
            allCount = iFacPrintOrderService.countAll(dealer);
            dealerCount = iSysUserBrokerageService.countAll(user);
        }
        JSONObject json = new JSONObject();
        double allProfit = allCount - dealerCount;
        json.put("allCount", allCount);
        json.put("dealerCount", dealerCount);
        json.put("allProfit", allProfit);
        return AjaxResult.success(json);
    }

    @Override
    public void brokerageReset() {
        sysDealerMapper.brokerageReset();
    }
}
